package com.itqf.controller;

import com.itqf.entity.Car;
import com.itqf.entity.User;
import com.itqf.service.CarService;
import com.itqf.service.impl.CarServiceImpl;
import com.itqf.utils.Constants;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/car")
public class CarController extends BaseServlet{
    public String creat(HttpServletRequest req, HttpServletResponse resp) throws IllegalAccessException, SQLException, InvocationTargetException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            session.setAttribute("msg","添加购物车请先登录！");
            return Constants.FOW+"/login.jsp";
        }
        int userno = user.getUserno();
        String gid = req.getParameter("gid");
        CarService carService = new CarServiceImpl();
        carService.createCar(userno,gid);

        return Constants.FOW+"/cartSuccess.jsp";
    }
    public String show(HttpServletRequest req, HttpServletResponse resp) throws IllegalAccessException, SQLException, InvocationTargetException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            session.setAttribute("msg","添加购物车请先登录！");
            return Constants.FOW+"/login.jsp";
        }

        int userno = user.getUserno();
        CarService carService = new CarServiceImpl();
       List<Car> list = carService.findAll(userno);
       req.setAttribute("list",list);

        return Constants.FOW+"/cart.jsp";
    }

    public String delete(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        String cid = req.getParameter("cid");
        CarService carService = new CarServiceImpl();
        carService.deleteCarByCid(cid);
        return Constants.FOW+"/car?method=show";
    }
    public String update(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        String cid = req.getParameter("cid");
        String gprice = req.getParameter("gprice");
        String number = req.getParameter("number");
        CarService carService = new CarServiceImpl();
        carService.updateCarByCid(cid,gprice,number);
        return Constants.FOW+"/car?method=show";
    }
    public String clear(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        String userno = req.getParameter("userno");

        CarService carService = new CarServiceImpl();
        carService.clearCar(userno);
        return Constants.FOW+"/car?method=show";
    }
}
